package com.leadingsoft.controller.download;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.cef.browser.CefBrowser;
import org.cef.callback.CefStringVisitor;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.leadingsoft.common.Constant;
import com.leadingsoft.common.TaskQuene;
import com.leadingsoft.common.model.MmJpgImageLog;

/**
 * @ClassName DownloadMmJpgImage
 * @Description 按照抓好的妹子ID下载每一个妹子的所有图片
 * @author gongym
 * @date 2018年6月22日 下午12:19:58
 */
public class DownloadMmJpgImage implements CefStringVisitor {
	private static Logger logger = LoggerFactory.getLogger(DownloadMmJpgImage.class);
	private CefBrowser browser;
	private String listSelector;
	private SQLManager sqlManager;
	private List<String> mmJpgIdList;

	public DownloadMmJpgImage(CefBrowser browser, String listSelector, SQLManager sqlManager,
			List<String> mmJpgIdList) {
		this.browser = browser;
		this.listSelector = listSelector;
		this.sqlManager = sqlManager;
		this.mmJpgIdList = mmJpgIdList;
	}
	@Override
	public void visit(String string) {
		String url = browser.getURL();
		logger.debug("开始下载图片，URL：{}", url);
		Document htmlDocument = Jsoup.parse(string);
		// 需要取出图片地址
		Elements elementsByClass = htmlDocument.getElementsByClass(listSelector);
		if (null != elementsByClass && elementsByClass.size() > 0) {
			MmJpgImageLog mmJpgImageLogTemplate = new MmJpgImageLog();
			mmJpgImageLogTemplate.setSpideredUrl(url);
			MmJpgImageLog mmJpgImageLog = sqlManager.templateOne(mmJpgImageLogTemplate);
			if (null == mmJpgImageLog) {
				logger.debug("当前页面的图片没有下载过，开始下载");
				Element element = elementsByClass.get(0);
				Elements imgs = element.select("#content>a>img");
				if (null != imgs && imgs.size() > 0) {
					Element img = imgs.get(0);
					// http://fm.shiyunjj.com/2018/1389/44igx.jpg
					String imgPath = img.attr("src");
					logger.debug("获取到妹子图片地址，开始进行下载：{}", imgPath);
					try {
						Map<String, String> headers = new HashMap<String, String>();
						headers.put("Referer", url);
						headers.put("User-Agent",
								"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36");
						Connection.Response response = Jsoup.connect(imgPath).headers(headers).ignoreContentType(true)
								.execute();
						byte[] imgBytes = response.bodyAsBytes();
						String savePathTemp = StringUtils.remove(imgPath, Constant.MMJPGIMGURLTEMP);
						StringBuilder savePath = new StringBuilder(Constant.MMJPGSAVEPATH);
						savePath.append(savePathTemp);
						FileUtils.writeByteArrayToFile(new File(savePath.toString()), imgBytes);
						logger.debug("下载文件保存成功，地址：{}", savePath.toString());
					} catch (IOException e) {
						e.printStackTrace();
						logger.debug("下载文件保存失败：{}", e.getMessage());
					}
				}
			}
		}
		// 无论如何都要开始下一页的页面加载
		logger.debug("保存当前页面的图片完毕，开始保存日志");
		MmJpgImageLog nowMmJpgImageLog = new MmJpgImageLog();
		nowMmJpgImageLog.setSpideredUrl(url);
		sqlManager.insert(nowMmJpgImageLog);
		logger.debug("插入当前URL到日志表");
		// 需要判断是否有下一页
		Boolean isNext = false;
		Elements nextElementsByClass = htmlDocument.getElementsByClass("next");
		if (null != nextElementsByClass && nextElementsByClass.size() > 0) {
			Element nextElement = nextElementsByClass.get(0);
			String nextElementText = nextElement.text();
			if (nextElementText.equals("下一张")) {
				isNext = true;
			}
		}
		logger.debug("判断是否存在下一页：{}", isNext);
		String nextUrl = TaskQuene.getMmJpgImageUrl(isNext, url, mmJpgIdList);
		if (StringUtils.isNotEmpty(nextUrl)) {
			TaskQuene.mmJpgImageTaskUrl.add(nextUrl.toString());
			logger.debug("获取到下一页URL为：{}", nextUrl);
			logger.debug("当前队列中的URL为：{}", TaskQuene.mmJpgTaskUrl);
			logger.debug("===================={}任务结束====================", nextUrl);
		} else {
			// 当前任务结束。关闭浏览器
			logger.debug("未获取到下一页URL，抓取任务结束");
			browser.close();
		}
	}
}
